//
//  AssetViewController.swift
//  GifUsage
//
//  Created by Ting Han on 2020/12/19.
//  Copyright © 2020 Ting Han. All rights reserved.
//

import UIKit
import Photos

class AssetViewController: UIViewController {
    
    var fetchResult: PHFetchResult<PHAsset>!
    var currentIndex: Int = 0
    
    var selectedIndexChanged: ((Int) -> Void)?
    override func viewDidLoad() {
        super.viewDidLoad()
        commonInit()
    }
    
    private var itemWidth: CGFloat = 0
    
    lazy var flowLayout: UICollectionViewFlowLayout = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.scrollDirection = .horizontal
        return flowLayout
    }()
    
    lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: flowLayout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isPagingEnabled = true
        collectionView.backgroundColor = .clear
        if #available(iOS 11, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        return collectionView
    }()
    
    lazy var bottomToolView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 100))
        view.addSubview(progressView)
        view.addSubview(playButton)
        progressView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 30)
        playButton.frame = CGRect(x: 0, y: progressView.frame.maxY + 30, width: 60, height: 30)
        return view
    }()
    
    lazy var progressView: UIProgressView = {
        let progressView = UIProgressView()
        return progressView
    }()
    
    lazy var playButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("play", for: .normal)
        button.backgroundColor = .cyan
        button.addTarget(self, action: #selector(playAction), for: .touchUpInside)
        return button
    }()
    
    deinit {
        print("deinit AssetViewController ")
    }
}

// MARK: Private
extension AssetViewController {
    private func commonInit() {
        setupNavigationBar()
        setupSubviews()
    }
    
    private func setupNavigationBar() {
        navigationItem.title = "相簿"
        view.backgroundColor = .white
        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationController?.navigationBar.shadowImage = UIImage()
    }
    
    private func setupSubviews() {
        view.addSubview(collectionView)
        collectionView.register(AssetCell.self, forCellWithReuseIdentifier: String(describing: AssetCell.self))
        collectionView.frame = view.bounds
        itemWidth = view.bounds.width
        flowLayout.itemSize = CGSize(width: itemWidth, height: view.bounds.height)
        collectionView.scrollToItem(at: IndexPath(item: currentIndex, section: 0), at: .left, animated: false)
        view.addSubview(bottomToolView)
        bottomToolView.frame = CGRect(x: 0, y: view.bounds.height - 100, width: view.bounds.width, height: 100)
    }
    
    @objc func playAction() {
        if let cell =  collectionView.visibleCells.first as? AssetCell {
            if cell.isPlaying {
                cell.pause()
            } else {
                cell.play()
            }
        }
    }
}
// MARK: UICollectionViewDelegate
extension AssetViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        fetchResult.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let asset = fetchResult.object(at: indexPath.item)
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: AssetCell.self), for: indexPath) as! AssetCell
        cell.asset = asset
        cell.progressHandler = { [weak self] progress  in
            DispatchQueue.main.async {
                guard let self = self else { return }
                self.progressView.progress = Float(progress)
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        if let cell = cell as? AssetCell {
            cell.pause()
        }
    }
}

extension AssetViewController {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let index = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        if currentIndex != index {
            currentIndex = index
            selectedIndexChanged?(index)
        }
    }
}
